package com.hao.controller;
import com.hao.mapper.UserMapper;
import com.hao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@Controller
public class UserController {
    @Autowired
    private UserMapper mapper;
    //网页部分
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @GetMapping("/loginto")
    public String loginto(String username, String password, HttpSession httpSession) {
        if("admin".equals(username)&&"admin".equals(password)){
            httpSession.setAttribute("user","user");
            return "redirect:/index";
        }else
            return "redirect:login";
    }
    @GetMapping("/index")
    public String index(HttpSession httpSession){
        if (httpSession!=null){
            return "index";
        }
        return "redirect:login";
    }
    @GetMapping("/dynamic")
    public String dynamic(){
        return "dynamic_table";
    }
    //User部分
    @GetMapping("/select")
    public String select(ModelMap model)  {
        List<User> users = mapper.SelectAll();
        model.put("list",users);
        for (User user : users) {
            System.out.println(user);
        }
        return "select";
    }
    @GetMapping("/add")
    public String add(){
        return "add";
    }
    @GetMapping("/add_commit")
    public String add_commit(String name,String age,String hobby){
        mapper.add(new User(name,age,hobby));
        return "redirect:/dynamic";
    }
    @GetMapping("/delete")
    public String delete(int id) {
        int i = mapper.SelectId(id);
        System.out.println(i);
        if(i!=0){
            mapper.delete(i);
        }
        return "redirect:/dynamic";
    }
    @GetMapping("/update")
    public String update(int id,ModelMap map) throws IOException {
        int i = mapper.SelectId(id);
        map.put("id",i);
        if( id==i ){
            return "update";
        }else{
            return "redirect:/dynamic";
        }

    }
    @GetMapping("/updateto")
    public String updateto(@RequestParam("id") int id, String name, String age, String hobby){
        mapper.update(new User(id,name,age,hobby));
        System.out.println("修改成功");
        return "redirect:/dynamic";
    }
}